package com.yunshang.shoppingmall.controller.product;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.yunshang.shoppingmall.common.LayUIUtil;
import com.yunshang.shoppingmall.common.UploadImgs;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Controller
public class ProductListController {

    @Autowired
    ProductService productService;
    @Autowired
    ProductClassfyService productClassfyService;
    @Autowired
    ProductGuiGeService productGuiGeService;
    private int productId = 0;
    private int productIds = 0;
    @Autowired
    GuiGePriceService guiGePriceService;
    @Autowired
    ProductPriceService productPriceService;
    private String updateGuiGeImgPath = "";//规格图路径
    List guigeGroupList = new ArrayList();//图组
    private String groupImgsPath = "";//图组路径

    //打开商品列表页
    @RequestMapping("/openProductList")
    public ModelAndView openProductList(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("product/productList01");
        return modelAndView;
    }

    //获取商品列表数据
    @ResponseBody
    @RequestMapping("/getProductListData")
    public LayUIUtil getProductListData(HttpServletRequest request) {
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        int pages = 0;
        int limits = 10;
        int activeSign = 0;
        if (page != null && page != "") {
            pages = Integer.parseInt(page);
        }
        if (limit != null && limit != "") {
            Integer.parseInt(page);
        }
        String activeSign1=request.getParameter("activeSign");
        if(activeSign1!=null&&activeSign1!=""){activeSign=Integer.parseInt(activeSign1);}
        String productName=request.getParameter("productName");
        Product product=new Product();
        product.setActiveSign(activeSign);
        product.setProductName(productName);
        PageHelper.startPage(pages, limits);
        List<ProductClassfy> productClassfyList = productClassfyService.selectProductClassfy(product);
        PageInfo pageInfo = new PageInfo(productClassfyList);
        int count = 0;
        count = (int) pageInfo.getTotal();
        return LayUIUtil.data(count, productClassfyList);
    }


    //编辑商品
    @ResponseBody
    @RequestMapping("editorProduct")
    public ModelAndView editorProduct(@RequestParam String productIds) {
        ModelAndView modelAndView = new ModelAndView("product/editorProduct");
        if (productIds != null && productIds != "") {
            productId = Integer.parseInt(productIds);
        }
        Product product = productService.selectByPrimaryKey(productId);
        modelAndView.addObject("product", product);
        return modelAndView;
    }

    //更新商品数据
    @ResponseBody
    @RequestMapping(value = "/updateProductData", method = RequestMethod.POST)
    public Map<String, Object> updateProductData(@RequestParam Map<String, String> map) {
        Map<String, Object> map1 = new HashMap<>();
        int productId = 0;
        String productName = null;
        int classId = 0;
        String productUnit = null;
        int activeSign = 0;
        String productUpState = "N";
        Timestamp uptime = null;
        String supplier;
        String productshortnamer = null;
        String productDesc = null;
        int row = 0;

        Product product = new Product();
        if (map != null) {
            product.setProductDesc(map.get("productDesc"));
            product.setProductName(map.get("productName"));
            product.setProductUnit(map.get("productUnit"));
            product.setSupplier(map.get("supplier"));
            product.setProductshortname(map.get("productshortnamer"));
            if (map.get("classId") != null) {
                classId = Integer.parseInt(map.get("classId"));
            }
            product.setClassId(classId);
            if (map.get("productId") != null) {
                productId = Integer.parseInt(map.get("productId"));
            }
            product.setProductId(productId);

            if ("上架".equals(map.get("productUpState"))) {
                productUpState = "Y";
            }
            product.setProductUpState(productUpState);

            Timestamp uptimes = new Timestamp(System.currentTimeMillis());
            product.setUptime(uptimes);
            int sorts = 0;
            if (map.get("sort") != null && map.get("sort") != "") {
                sorts = Integer.parseInt(map.get("sort"));
            }
            product.setSort(sorts);
            row = productService.updateByPrimaryKeySelective(product);
            if (row > 0) {
                map1.put("msg", "1");
            }
        }
        return map1;
    }


    //删除商品
    @ResponseBody
    @RequestMapping("/delProductData")
    public Map<String, Object> delProductData(@RequestParam String productIds) {
        Map<String, Object> map = new HashMap<>();
        int guigeId = 0;
        int row = 0;
        int rows = 0;
        int proRow = 0;
        if (productIds != null && productIds != "") {
            productId = Integer.parseInt(productIds);
        }
        //查询规格
        List<ProductGuiGe> productGuiGeList = productGuiGeService.selectGuigeListByProductId(productId);
        if (productGuiGeList != null && productGuiGeList.size() != 0) {
            for (int i = 0; i < productGuiGeList.size(); i++) {
                if (productGuiGeList.get(i) != null) {//存在规格
                    guigeId = productGuiGeList.get(i).getGuigeId();
                    if (guigeId != 0) {
                        ProductPrice productPrice = productPriceService.selectProductPriceByGuigeId(guigeId);
                        if (productPrice != null) {//存在价格
                            //删除价格
                            row = productPriceService.deleteByPrimaryKey(productPrice.getPriceId());
                        }
                    }
                    //删除规格
                    rows = productGuiGeService.deleteByPrimaryKey(guigeId);
                }
            }
        }
        //没有商品规格直接删除商品
        proRow = productService.deleteByPrimaryKey(productId);
        if (proRow > 0) {
            map.put("msg", "1");
        }
        return map;
    }


    //查询规格
    @RequestMapping("/openGuiGeDetails")
    public ModelAndView openGuiGeDetails(HttpServletRequest request) {
        String proId = request.getParameter("productId");
        ModelAndView modelAndView = new ModelAndView("product/guigeDetails");
        if (proId != null && proId != "") {
            productId = Integer.parseInt(proId);
        }
        modelAndView.addObject("proId", proId);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/getGuiGePriceData")
    public LayUIUtil getGuiGePriceData(HttpServletRequest request) {
        List<GuiGePrice> guiGePriceList = guiGePriceService.selectGuiGePriceByProId(productId);
        LayUIUtil layUIUtil = new LayUIUtil();
        PageInfo<GuiGePrice> pricePageInfo = new PageInfo<>(guiGePriceList);

        return layUIUtil.data((int) pricePageInfo.getTotal(), pricePageInfo.getList());
    }

    //


    //编辑规格
    @RequestMapping("/editorGuiGe")
    public ModelAndView editorGuiGe(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("product/editorGuige");
        String guigeId = request.getParameter("guigeId");
        int guigeIds = 0;
        if (guigeId != null && guigeId != "") {
            guigeIds = Integer.parseInt(guigeId);
        }
        GuiGePrice guiGePrice = guiGePriceService.selectGuiGePriceByguigeId(guigeIds);
        System.out.println("------------返代金券----->" + guiGePrice.getOtherRank());
        if (guiGePrice != null) {
            String imgGroup = guiGePrice.getImgGroup();
            String[] arr = new String[10];
            arr = imgGroup.split(",");
            modelAndView.addObject("imgarr", arr);
            modelAndView.addObject("guigePrice", guiGePrice);
        }
        return modelAndView;
    }

    //修改规格价格
    @ResponseBody
    @RequestMapping(value = "/updateGuiGePrice", method = RequestMethod.POST)
    public Map<String, Object> updateGuiGePrice(@RequestParam Map<String, String> map1) {
        Map<String, Object> map = new HashMap<>();

        int guigeId = 0;
        int productId = 0;
        double proSize = 0.00;
        double proWeight = 0.00;
        double proTiji = 0.00;
        String proColor = null;
        String proOther = null;
        String fendan = null;
        double proLength = 0.00;
        double proHeight = 0.00;
        double proWidth = 0.00;
        String imgurl = null;
        double proVolume = 0.00;
        String guigeName = null;
        int priceId = 0;
        BigDecimal opratorCost = null;
        BigDecimal productCost = null;
        BigDecimal coupon = null;
        BigDecimal marketprice = null;
        int huiyuan = 0;
        int dianzhu = 0;
        int yzDianzhu = 0;
        BigDecimal proPrice = null;
        int visitor = 0;
        int otherRank = 0;
        String buySign = "";
        String commissionSign = "";
        int buyCountTotal = 0;
        int buyCount = 0;
        String imgGroup = null;
        int rows = 0;
        int row = 0;

        //规格价格对象
        GuiGePrice guiGePrice = new GuiGePrice();
        if (map1.get("guigeId") != null && map1.get("guigeId") != "") {
            guigeId = Integer.parseInt(map1.get("guigeId"));
        }
        if (map1.get("productId") != null && map1.get("productId") != "") {
            productId = Integer.parseInt(map1.get("productId"));
        }
        if (map1.get("proSize") != null && map1.get("proSize") != "") {
            proSize = Double.parseDouble(map1.get("proSize"));
        }
        if (map1.get("proWeight") != null && map1.get("proWeight") != "") {
            proWeight = Double.parseDouble(map1.get("proWeight"));
        }
        if (map1.get("proTiji") != null && map1.get("proTiji") != "") {
            proTiji = Double.parseDouble(map1.get("proTiji"));
        }
        if (map1.get("proLength") != null && map1.get("proLength") != "") {
            proLength = Double.parseDouble(map1.get("proLength"));
        }
        if (map1.get("proHeight") != null && map1.get("proHeight") != "") {
            proHeight = Double.parseDouble(map1.get("proHeight"));
        }
        if (map1.get("proWidth") != null && map1.get("proWidth") != "") {
            proWidth = Double.parseDouble(map1.get("proWidth"));
        }
        if (map1.get("proVolume") != null && map1.get("proVolume") != "") {
            proVolume = Double.parseDouble(map1.get("proVolume"));
        }
        if (map1.get("buySign") != null && map.get("buySign") != "") {
            buySign = map1.get("buySign");
        }
        if (map1.get("commissionSign") != null && map.get("commissionSign") != "") {
            commissionSign = map1.get("commissionSign");
        }
        if (map1.get("buyCountTotal") != null && map.get("buyCountTotal") != "") {
            buyCountTotal = Integer.parseInt(map1.get("buyCountTotal"));
        }
        if (map1.get("buyCount") != null && map.get("buyCount") != "") {
            buyCount = Integer.parseInt(map1.get("buyCount"));
        }

        if (map1.get("priceId") != null && map1.get("priceId") != "") {
            priceId = Integer.parseInt(map1.get("priceId"));
        }
        if (map1.get("opratorCost") != null && map1.get("opratorCost") != "") {
            opratorCost = new BigDecimal(map1.get("opratorCost"));
        }
        if (map1.get("productCost") != null && map1.get("productCost") != "") {
            productCost = new BigDecimal(map1.get("productCost"));
        }
        if (map1.get("coupon") != null && map1.get("coupon") != "") {
            coupon = new BigDecimal(map1.get("coupon"));
        }
        if (map1.get("marketprice") != null && map1.get("marketprice") != "") {
            marketprice = new BigDecimal(map1.get("marketprice"));
        }
        if (map1.get("proPrice") != null && map1.get("proPrice") != "") {
            proPrice = new BigDecimal(map1.get("proPrice"));
        }
        if (map1.get("huiyuan") != null && map1.get("huiyuan") != "") {
            huiyuan = Integer.parseInt(map1.get("huiyuan"));
        }
        if (map1.get("dianzhu") != null && map1.get("dianzhu") != "") {
            dianzhu = Integer.parseInt(map1.get("dianzhu"));
        }
        if (map1.get("yzDianzhu") != null && map1.get("yzDianzhu") != "") {
            yzDianzhu = Integer.parseInt(map1.get("yzDianzhu"));
        }
        if (map1.get("visitor") != null && map1.get("visitor") != "") {
            visitor = Integer.parseInt(map1.get("visitor"));
        }
        if (map1.get("otherRank") != null && map1.get("otherRank") != "") {
            otherRank = Integer.parseInt(map1.get("otherRank"));
        }

        //规格
        ProductGuiGe productGuiGe = new ProductGuiGe();

        //图组路径
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < guigeGroupList.size(); i++) {
            sb.append(guigeGroupList.get(i) + ",");
        }
        imgGroup = sb.toString();
        if (guigeGroupList != null && guigeGroupList.size() != 0) {
            productGuiGe.setImgGroup(imgGroup);
        }
        if (updateGuiGeImgPath != null && updateGuiGeImgPath != "") {
            productGuiGe.setImgurl(updateGuiGeImgPath);
        }

        imgGroup = null;
        updateGuiGeImgPath = null;
        guigeGroupList.clear();
        productGuiGe.setProColor(map1.get("proColor"));
        productGuiGe.setProHeight(proHeight);
        productGuiGe.setProLength(proLength);
        productGuiGe.setProOther(map1.get("proOther"));
        productGuiGe.setProSize(proSize);
        productGuiGe.setProTiji(proTiji);
        productGuiGe.setProVolume(proVolume);
        productGuiGe.setGuigeId(guigeId);
        productGuiGe.setGuigeName(map1.get("guigeName"));
        productGuiGe.setProWidth(proWidth);
        productGuiGe.setFendan(map1.get("fendan"));
        productGuiGe.setProWeight(proWeight);
        productGuiGe.setProductId(productId);
        productGuiGe.setBuySign(buySign);
        productGuiGe.setCommissionSign(commissionSign);
        productGuiGe.setBuyCountTotal(buyCountTotal);
        productGuiGe.setBuyCount(buyCount);


        //价格
        ProductPrice productPrice = new ProductPrice();
        productPrice.setCoupon(coupon);
        productPrice.setDianzhu(dianzhu);
        productPrice.setHuiyuan(huiyuan);
        productPrice.setVisitor(visitor);
//        productPrice.setGuigeId(guigeId);
        productPrice.setMarketprice(marketprice);
        productPrice.setOpratorCost(opratorCost);
        productPrice.setProductCost(productCost);
        productPrice.setProductId(productId);
        productPrice.setProPrice(proPrice);
        productPrice.setYzDianzhu(yzDianzhu);
        productPrice.setPriceId(priceId);
        productPrice.setOtherRank(otherRank);
        //更新价格
        row = productGuiGeService.updateByPrimaryKeySelective(productGuiGe);
        if (row > 0) {
            rows = productPriceService.updateByPrimaryKeySelective(productPrice);
        }

        if (row > 0 && rows > 0) {

            map.put("msg", "1");
        }
        sb = null;
        imgGroup = null;

        return map;
    }

    //删除规格
    @ResponseBody
    @RequestMapping("/delGuiGeAndPrice")
    public Map<String, Object> delGuiGeAndPrice(@RequestParam String guigeId, String priceId) {
        Map<String, Object> map = new HashMap<>();
        int priceIds = 0;
        int guigeIds = 0;
        int row = 0;
        int rows = 0;
        if (priceId != null && priceId != "") {
            priceIds = Integer.parseInt(priceId);
        }
        if (guigeId != null && guigeId != "") {
            guigeIds = Integer.parseInt(guigeId);
        }
        //删除价格

        row = productPriceService.deleteByPrimaryKey(priceIds);
        rows = productGuiGeService.deleteByPrimaryKey(guigeIds);

        if (rows > 0) {
            map.put("msg", "1");
        }
        return map;
    }

    /*编辑商品---上传图片*/
    @ResponseBody
    @RequestMapping(value = "/upProImg", method = RequestMethod.POST)
    public Map<String, Object> upProductImg(MultipartFile file, HttpServletRequest request) {
        Logger logger = LoggerFactory.getLogger(ProductListController.class);
        Map<String, Object> map = new HashMap<>();
        String productId = request.getParameter("productId");
        int productIds = 0;
        String[] relativePath = null;
        String uploadImgPath = null;
        String uploadFileName = null;
        String imgsPath = null;
        if (productId != null && productId != "") {
            productIds = Integer.parseInt(productId);
        }
        String filename = file.getOriginalFilename();
        try {
            uploadFileName = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
            map = UploadImgs.uploads(file);
            imgsPath = (String) map.get("imagePath");

            //更新相对路径
            Product product = new Product();
            product.setProImg(imgsPath);
            product.setProductId(productIds);
            int row = productService.updateByPrimaryKeySelective(product);
            logger.info("保存图片先对路径：" + imgsPath);
            if (row > 0) {
                map.put("msg", "1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /*编辑商品-------商品详情图*/
    @ResponseBody
    @RequestMapping(value = "/uploadProDetailImg", method = RequestMethod.POST)
    public Map<String, Object> uploadProDetailImg(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String productId = request.getParameter("productId");
        int productIds = 0;
        String productDetatilImgPath = "";
        String uploadFileName = null;

        if (productId != null && productId != "") {

            productIds = Integer.parseInt(productId);
        }

        try {

            map = UploadImgs.uploads(file);
            //详情图的相对路径
            productDetatilImgPath = (String) map.get("imagePath");


            //更新商品详情图路径
            Product product = new Product();
            product.setProductId(productIds);
            product.setDetailContent(productDetatilImgPath);
            int row = productService.updateByPrimaryKeySelective(product);
            if (row > 0) {
                map.put("msg", "1");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    //编辑规格----上传规格图
    @ResponseBody
    @RequestMapping(value = "/updateGuiGeImgs", method = RequestMethod.POST)
    public Map<String, Object> updateGuiGeImgs(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map = UploadImgs.uploads(file);
        updateGuiGeImgPath = (String) map.get("imagePath");
        System.out.println("imagePath:" + updateGuiGeImgPath);
        if (updateGuiGeImgPath != null && updateGuiGeImgPath != "") {
            map.put("msg", "1");
        }
        return map;
    }

    //编辑规格----上传图组
    @ResponseBody
    @RequestMapping(value = "/updateGuiGeGroupImgs", method = RequestMethod.POST)
    public Map<String, Object> updateGuiGeGroupImgs(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map = UploadImgs.uploads(file);
        groupImgsPath = (String) map.get("imagePath");
        guigeGroupList.add(groupImgsPath);
        System.out.println("imagePath:" + groupImgsPath);
        if (groupImgsPath != null && groupImgsPath != "") {
            map.put("msg", "1");
        }
        return map;
    }
}
